var _BG = {};

_BG.master_password = 'password';

_BG.prefs = {
	"encrypt-fields" : true,
	"encrypt-key" : false
};

_BG.save_form = function ( args )
{
	var res = { encrypted: _BG.master_password.length ? true : false };
	var dest = JSON.stringify ( args.fields );

	if ( _BG.master_password ) dest = Tea.encrypt ( dest, _BG.master_password );
	res [ "data" ] = dest;

	localStorage [ args.name ] = JSON.stringify ( res );
};

_BG.load_form = function ( args )
{
	var name = args.name;
	var res = localStorage [ name ];
	var data;

	if ( ! res ) return null;

	res = JSON.parse ( res );

	if ( res.encrypted ) res.data = Tea.decrypt ( res.data, _BG.master_password );

	return JSON.parse ( res [ 'data' ] );
};

_BG.set_master_password = function ( args )
{
	_BG.master_password = args.pwd;
};

_BG.get_master_password = function ( args )
{
	return _BG.master_password;
};

_BG.list_domains = function ( args )
{
	var res = [];
	var t, l = localStorage.length;
	
	for ( t = 0; t < l; t ++ ) res.push ( localStorage.key ( t ) );

	return res;
};

_BG.has_master_password = function ( args )
{
	var res = [];
	var t, l = localStorage.length;
	var data;
	
	for ( t = 0; t < l; t ++ ) 
	{
		data = JSON.parse ( localStorage [ localStorage.key ( t ) ] );

		if ( data.encrypted ) return true;
	}

	return false;
};

chrome.extension.onRequest.addListener (
	function ( request, sender, sendResponse ) 
	{
		if ( ! sender.tab ) return;

		switch ( request.mode )
		{
			case "load":
				sendResponse ( { data: _BG.load_form ( request ) } );
				break;
			case "save":
				sendResponse ( { data: _BG.save_form ( request ) } );
				break;

			case "get-master-password":
				sendResponse ( { data: _BG.get_master_password ( request ) } );
				break;

			case "set-master-password":
				sendResponse ( { data: _BG.get_master_password ( request ) } );
				break;

			case "list-domains":
				sendResponse ( { data: _BG.list_domains ( request ) } );
				break;

			case "has-master-password":
				sendResponse ( { data: _BG.has_master_password ( request ) } );
				break;
		}
	}
);
